package com.tql.mall.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.tql.mall.auth.service.UserService;
import com.tql.mall.common.constant.ComConstant;
import com.tql.mall.common.constant.RedisConstant;
import com.tql.mall.common.result.R;
import com.tql.mall.common.result.RC;
import com.tql.mall.common.util.ComUtil;
import com.tql.mall.common.util.IpUtil;
import com.tql.mall.model.base.BaseUser;
import com.tql.mall.model.customer.Customer;
import com.tql.mall.model.merchant.Merchant;
import com.tql.mall.model.user.Admin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tyk
 * @Date: 2023/5/24 19:28
 * @Description:
 */
@RestController
@RequestMapping("api/user/")
@Api(description = "认证中心")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 顾客登录
     */
    @PostMapping("customer/login")
    @ApiOperation("顾客登录")
    public R<BaseUser> loginCustomer(@RequestBody Customer customer, HttpServletRequest req) {
        // 查询用户
        Customer user = userService.loginCustomer(customer);
        // 返回用户
        return doLogin(user, req);
    }

    /**
     * 顾客登出
     */
    @GetMapping("customer/logout")
    @ApiOperation("顾客登出")
    public R<Void> logoutCustomer(HttpServletRequest req) {
        // 退出登录
        return doLogout(req);
    }

    /**
     * 商家登录
     */
    @PostMapping("merchant/login")
    @ApiOperation("商家登录")
    public R<BaseUser> loginMerchant(@RequestBody Merchant merchant, HttpServletRequest req) {
        // 查询用户
        Merchant user = userService.loginMerchant(merchant);
        // 返回用户
        return doLogin(user, req);
    }

    /**
     * 商家登出
     */
    @GetMapping("merchant/logout")
    @ApiOperation("商家登出")
    public R<Void> logoutMerchant(HttpServletRequest req) {
        // 退出登录
        return doLogout(req);
    }

    /**
     * 管理员登录
     */
    @PostMapping("admin/login")
    @ApiOperation("管理员登录")
    public R<BaseUser> loginAdmin(@RequestBody Admin admin, HttpServletRequest req) {
        // 查询用户
        Admin user = userService.loginAdmin(admin);
        // 返回用户
        return doLogin(user, req);
    }


    /**
     * 管理员登出
     */
    @GetMapping("admin/logout")
    @ApiOperation("管理员登出")
    public R<Void> logoutAdmin(HttpServletRequest req) {
        // 退出登录
        return doLogout(req);
    }


/**
 * 执行通用登录操作
 * 1.检查用户是否存在
 * 2.设置token
 * 3.登录信息（token与用户ID）存放到redis
 * 4.擦除密码
 */
private R<BaseUser> doLogin(BaseUser user, HttpServletRequest req) {
    if (user == null) return R.fail(RC.LOGIN_FAIL);
    // 获取token
    String token = ComUtil.uuid();
    // 获取当前用户的IP
    String ip = IpUtil.getIpAddress(req);
    // 存储到Redis
    JSONObject obj = new JSONObject();
    obj.put(ComConstant.USER_ID, user.getId());
    obj.put(ComConstant.IP, ip);
    redisTemplate.opsForValue().set(
            RedisConstant.USER_LOGIN_TOKEN_PREFIX + token, obj.toJSONString(), RedisConstant.USER_TOKEN_EXPIRE, TimeUnit.SECONDS
    );
    // 擦除密码并设置token
    user.setPasswd("");
    user.setToken(token);
    // 返回用户
    return R.ok(user);
}

    /**
     * 通用用户登出操作
     */
    private R<Void> doLogout(HttpServletRequest req) {
        // 清除Redis中的token
        String token = req.getHeader("token");
        redisTemplate.delete(RedisConstant.USER_LOGIN_TOKEN_PREFIX + token);
        return R.ok();
    }


}
